<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script>
class Scheduler {
    constructor () {
        this.runingTask = 0
        this.queue = []
        this.max = 2
    }
    add(promiseCreator) {
        this.queue.push(promiseCreator)
        this.startPromise()
    }
    startPromise () {
        // console.log('startPromise:', this.queue)
        if (this.queue && this.queue.length && (this.runingTask < this.max)) {
            this.runingTask++
            let task = this.queue.shift()
            // console.log('task:', task)
            task().then(() => {
                this.runingTask--
                this.startPromise()
            })
        }
    }
}
   
const timeout = time => new Promise(resolve => {
  setTimeout(resolve, time);
})
  
const scheduler = new Scheduler();
  
const addTask = (time,order) => {
  scheduler.add(() => timeout(time).then(()=>console.log(order)))
}

addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');

// output: 2 3 1 4


</script>
</body>
</html>